package top.loonglove.newindexserver.config;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.loonglove.common.util.factory.http.HttpResponseFactory;
import top.loonglove.common.util.http.HttpMethod;
import top.loonglove.common.util.http.HttpResponse;
import top.loonglove.common.util.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2021/7/26 4:57
 */
@ControllerAdvice
public class BaseControllerAdvice {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public HttpResponse defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        HttpMethod method;
        try {
            method = HttpMethod.valueOf(req.getMethod());
        }catch (Exception e1){
            method = HttpMethod.UNKNOWN;
        }

        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            return HttpResponseFactory.build().
                    requestMethod(method).
                    message("404 服务器无法根据客户端的请求找到资源").
                    error(e).
                    status(HttpStatus.NOT_FOUND).
                    errorMessage(e.getMessage()).
                    build();
        } else {
            return HttpResponseFactory.build().
                    requestMethod(method).
                    message("500 服务器内部错误，无法完成请求").
                    error(e).
                    status(HttpStatus.INTERNAL_SERVER_ERROR).
                    errorMessage(e.getMessage()).
                    build();
        }
    }

}
